import { useSettingStore } from '@renderer/stores'
import { Input, Upload } from 'antd'
import classNames from 'classnames'
import { useSearchIcon } from '@renderer/hooks'
import { Add, Reduce } from '@icon-park/react'
import { generateId } from '@renderer/utils'
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons'
import { useState } from 'react'
import styles from './styles.module.css'

export function SearchSetting () {
  const [loading, setLoading] = useState(false);
  const systemSearchItems = useSettingStore(s => s.systemSearchItems)
  const browserSearchItems = useSettingStore(s => s.browserSearchItems)
  const addBrowserSearchItem = useSettingStore(s => s.addBrowserSearchItem)
  const removeBrowserSearchItem
    = useSettingStore(s => s.removeBrowserSearchItem)
  const updateBrowserSearchItem
    = useSettingStore(s => s.updateBrowserSearchItem)
  const updateSystemSearchItem = useSettingStore(s => s.updateSystemSearchItem)
  const { renerSearchIcon } = useSearchIcon(
    styles.icon,
  )
  const iconUploader = (
    id: string,
    updater: (
      itemId: string,
      data: any
    ) => void,
  ) => (
    <Upload
      accept='image/*'
      listType="picture-card"
      className="search-icon-uploader"
      showUploadList={false}
      customRequest={options => {
        if (!options.file) return

        setLoading(true)
        const reader = new FileReader();

        reader.onload = async (event) => {
          if (!event.target || !event.target.result) return

          const buffer = window.api.toBuffer(
            event.target.result as ArrayBuffer,
          );
          try {
            const filePath = await window.api.saveImage(
              buffer,
              (options.file as File).name,
            )
            updater(id, {
              icon: `file:///${filePath.replace(/\\/g, '/')}`,
            })
          } catch {}
          setLoading(false)
        };

        reader.readAsArrayBuffer(options.file as Blob);
      }}
    >
      <button style={{ border: 0, background: 'none' }} type="button">
        {
          loading ? <LoadingOutlined /> : <PlusOutlined />
        }
      </button>
    </Upload>
  )
  
  return (
    <div className={styles.container}>
      <div className={styles.content}>
        <div className={styles.title}>系统搜索</div>
        {
          systemSearchItems.map(item => {
            const {
              id,
              visible = true,
              name,
              abbreviation,
            } = item
            if (!visible) return null

            return (
              <div
                className={styles.item}
                key={id}
              >
                <div className={styles.iconWrapper}>
                  {
                    renerSearchIcon(
                      item,
                      name,
                      iconUploader(id, updateSystemSearchItem),
                    )
                  }
                </div>
                <Input
                  value={name}
                  className={styles.nameInput}
                  onChange={e => {
                    updateSystemSearchItem(id, {
                      name: e.target.value,
                    })
                    window.api.reloadWindow('search')
                  }}
                />
                <Input
                  value={abbreviation}
                  className={styles.abbrInput}
                  onChange={e => {
                    updateSystemSearchItem(id, {
                      abbreviation: e.target.value,
                    })
                    window.api.reloadWindow('search')
                  }}
                />
              </div>
            )
          })
        }
        <div
          className={classNames(styles.title, styles.browserTitle)}
        >
          浏览器搜索
        </div>
        {
          browserSearchItems.map(item => {
            const {
              id,
              visible = true,
              name,
              abbreviation,
              url,
            } = item
            if (!visible) return null

            return (
              <div
                className={styles.item}
                key={id}
              >
                <div className={styles.iconWrapper}>
                  { renerSearchIcon(
                    item, name, iconUploader(id, updateBrowserSearchItem)) }
                </div>
                <Input
                  value={name}
                  className={styles.nameInput}
                  onChange={e => {
                    updateBrowserSearchItem(id, {
                      name: e.target.value,
                    })
                    window.api.reloadWindow('search')
                  }}
                />
                <Input
                  value={abbreviation}
                  className={styles.abbrInput}
                  onChange={e => {
                    updateBrowserSearchItem(id, {
                      abbreviation: e.target.value,
                    })
                    window.api.reloadWindow('search')
                  }}
                />
                <Input
                  value={url}
                  className={styles.urlInput}
                  onChange={e => {
                    updateBrowserSearchItem(id, {
                      url: e.target.value,
                    })
                    window.api.reloadWindow('search')
                  }}
                />
                <Reduce
                  theme="outline"
                  size="24"
                  fill="currentColor"
                  className='text-gray-500 cursor-pointer'
                  onClick={() => {
                    removeBrowserSearchItem(id)
                  }}
                />
              </div>
            )
          })
        }
        <div
          className={classNames(
            styles.item,
            styles.plusItem,
          )}
        >
          <Add
            theme="outline"
            size="24"
            fill="currentColor"
            className='text-gray-500 cursor-pointer'
            onClick={() => {
              addBrowserSearchItem({
                id: generateId(),
                type: '',
                name: '',
                icon: '',
                abbreviation: '',
                url: '',
              })
            }}
          />
        </div>
      </div>
    </div>
  )
}
